package com.djf.util;

import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 数据生成器 - 用于生成大量用户和物流测试数据
 * 
 * @author djf
 * @date 2025-01-01
 */
public class DataGenerator {
    
    private static final Random random = new Random();
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 省份城市数据
    private static final String[][] PROVINCES_CITIES = {
        {"北京市", "北京市", "朝阳区,海淀区,西城区,东城区,丰台区,石景山区"},
        {"上海市", "上海市", "浦东新区,黄浦区,徐汇区,长宁区,静安区,普陀区"},
        {"广东省", "广州市", "天河区,越秀区,海珠区,荔湾区,白云区,黄埔区"},
        {"广东省", "深圳市", "南山区,福田区,罗湖区,盐田区,宝安区,龙岗区"},
        {"浙江省", "杭州市", "西湖区,拱墅区,江干区,下城区,上城区,滨江区"},
        {"江苏省", "南京市", "玄武区,秦淮区,建邺区,鼓楼区,浦口区,栖霞区"},
        {"四川省", "成都市", "锦江区,青羊区,金牛区,武侯区,成华区,龙泉驿区"},
        {"湖北省", "武汉市", "江岸区,江汉区,硚口区,汉阳区,武昌区,青山区"},
        {"陕西省", "西安市", "新城区,碑林区,莲湖区,灞桥区,未央区,雁塔区"},
        {"山东省", "青岛市", "市南区,市北区,四方区,黄岛区,崂山区,李沧区"}
    };
    
    // 快递公司
    private static final String[] DELIVERY_COMPANIES = {
        "顺丰速运", "圆通速递", "中通快递", "韵达速递", "申通快递", 
        "邮政EMS", "德邦快递", "百世快递", "天天快递", "优速快递"
    };
    
    // 快递公司前缀
    private static final String[] COMPANY_PREFIXES = {
        "SF", "YT", "ZT", "YD", "ST", "EMS", "DB", "BS", "TT", "YS"
    };
    
    // 姓氏
    private static final String[] SURNAMES = {
        "王", "李", "张", "刘", "陈", "杨", "赵", "黄", "周", "吴",
        "徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗",
        "梁", "宋", "郑", "谢", "韩", "唐", "冯", "于", "董", "萧"
    };
    
    // 名字
    private static final String[] GIVEN_NAMES = {
        "伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军",
        "洋", "勇", "艳", "杰", "娟", "涛", "明", "超", "秀兰", "霞",
        "平", "刚", "桂英", "建华", "文", "华", "金凤", "素华", "建国", "德华"
    };
    
    public static void main(String[] args) {
        try {
            generateUserData(1000);
            generateDeliveryData(1000);
            System.out.println("数据生成完成！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 生成用户数据
     */
    public static void generateUserData(int count) throws IOException {
        FileWriter writer = new FileWriter("user_data.sql");
        writer.write("-- 生成的用户数据\n");
        writer.write("USE sharding_order_db;\n\n");
        
        // 分批插入，每批500条
        int batchSize = 500;
        for (int batch = 0; batch < (count + batchSize - 1) / batchSize; batch++) {
            writer.write("INSERT INTO `t_user` (`id`, `user_name`, `phone`, `email`, `gender`, `tenant_id`, `create_time`) VALUES\n");
            
            int startId = batch * batchSize + 30001; // 从30001开始
            int endId = Math.min(startId + batchSize - 1, 30001 + count - 1);
            
            for (int i = startId; i <= endId; i++) {
                String userName = generateRandomName();
                String phone = generatePhone(i);
                String email = generateEmail(i);
                int gender = random.nextInt(2) + 1; // 1或2
                long tenantId = 1001 + (i % 3); // 1001, 1002, 1003循环
                String createTime = generateRandomTime(2024, 1, 12);
                
                writer.write(String.format("(%d, '%s', '%s', '%s', %d, %d, '%s')",
                    i, userName, phone, email, gender, tenantId, createTime));
                
                if (i < endId) {
                    writer.write(",\n");
                } else {
                    writer.write(";\n\n");
                }
            }
        }
        
        writer.close();
        System.out.println("用户数据生成完成: user_data.sql");
    }
    
    /**
     * 生成物流数据
     */
    public static void generateDeliveryData(int count) throws IOException {
        FileWriter writer = new FileWriter("delivery_data.sql");
        writer.write("-- 生成的物流数据\n");
        writer.write("USE sharding_order_db;\n\n");
        
        // 为每个月生成数据
        String[] months = {"202501", "202502", "202503"};
        int recordsPerMonth = count / 3;
        
        for (int monthIndex = 0; monthIndex < months.length; monthIndex++) {
            String month = months[monthIndex];
            writer.write(String.format("-- %s年%s月物流数据\n", 
                month.substring(0, 4), month.substring(4, 6)));
            
            // 分批插入
            int batchSize = 200;
            for (int batch = 0; batch < (recordsPerMonth + batchSize - 1) / batchSize; batch++) {
                writer.write(String.format("INSERT INTO `user_delivery_%s` (`user_id`, `order_id`, `delivery_no`, `receiver_name`, `receiver_phone`, `delivery_address`, `province`, `city`, `district`, `delivery_status`, `courier_name`, `courier_phone`, `delivery_company`, `tracking_number`, `create_time`) VALUES\n", month));
                
                int startIndex = batch * batchSize;
                int endIndex = Math.min(startIndex + batchSize - 1, recordsPerMonth - 1);
                
                for (int i = startIndex; i <= endIndex; i++) {
                    int recordId = monthIndex * recordsPerMonth + i + 1;
                    long userId = 30001 + (recordId % 1000); // 对应用户ID
                    long orderId = 200001 + recordId; // 订单ID
                    String deliveryNo = String.format("DEL%s%05d", month, recordId);
                    String receiverName = generateRandomName();
                    String receiverPhone = generatePhone((int)userId);
                    
                    // 随机选择省市区
                    String[] location = getRandomLocation();
                    String province = location[0];
                    String city = location[1];
                    String district = location[2];
                    String address = String.format("%s%s%s%s大道%d号", province, city, district, 
                        generateRandomStreetName(), random.nextInt(999) + 1);
                    
                    int deliveryStatus = random.nextInt(4) + 1; // 1-4
                    String courierName = generateRandomName();
                    String courierPhone = generateCourierPhone();
                    int companyIndex = random.nextInt(DELIVERY_COMPANIES.length);
                    String deliveryCompany = DELIVERY_COMPANIES[companyIndex];
                    String trackingNumber = String.format("%s%s%05d", 
                        COMPANY_PREFIXES[companyIndex], month, recordId);
                    
                    String createTime = generateRandomTimeInMonth(2025, monthIndex + 1);
                    
                    writer.write(String.format("(%d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s')",
                        userId, orderId, deliveryNo, receiverName, receiverPhone, address,
                        province, city, district, deliveryStatus, courierName, courierPhone,
                        deliveryCompany, trackingNumber, createTime));
                    
                    if (i < endIndex) {
                        writer.write(",\n");
                    } else {
                        writer.write(";\n\n");
                    }
                }
            }
        }
        
        writer.close();
        System.out.println("物流数据生成完成: delivery_data.sql");
    }
    
    private static String generateRandomName() {
        String surname = SURNAMES[random.nextInt(SURNAMES.length)];
        String givenName = GIVEN_NAMES[random.nextInt(GIVEN_NAMES.length)];
        return surname + givenName;
    }
    
    private static String generatePhone(int seed) {
        return String.format("138%08d", seed % 100000000);
    }
    
    private static String generateEmail(int seed) {
        return String.format("user%d@example.com", seed);
    }
    
    private static String generateCourierPhone() {
        return String.format("139%08d", random.nextInt(100000000));
    }
    
    private static String generateRandomTime(int year, int startMonth, int endMonth) {
        int month = random.nextInt(endMonth - startMonth + 1) + startMonth;
        int day = random.nextInt(28) + 1; // 简化处理，都用28天
        int hour = random.nextInt(24);
        int minute = random.nextInt(60);
        int second = random.nextInt(60);
        
        LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute, second);
        return dateTime.format(formatter);
    }
    
    private static String generateRandomTimeInMonth(int year, int month) {
        int day = random.nextInt(28) + 1;
        int hour = random.nextInt(24);
        int minute = random.nextInt(60);
        int second = random.nextInt(60);
        
        LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute, second);
        return dateTime.format(formatter);
    }
    
    private static String[] getRandomLocation() {
        String[] provinceCity = PROVINCES_CITIES[random.nextInt(PROVINCES_CITIES.length)];
        String[] districts = provinceCity[2].split(",");
        String district = districts[random.nextInt(districts.length)];
        return new String[]{provinceCity[0], provinceCity[1], district};
    }
    
    private static String generateRandomStreetName() {
        String[] streetNames = {"建设", "人民", "中山", "解放", "和平", "友谊", "光明", "胜利", "东方", "西湖"};
        return streetNames[random.nextInt(streetNames.length)];
    }
}